﻿using System;
using System.ComponentModel;

namespace MyFramework.Command.DelegateWatchCommand
{
    /// <summary>
    /// Property watch trigger
    /// </summary>
    public class PropertyWatchTrigger
    {
        #region Fields

        /// <summary>
        /// The watch
        /// </summary>
        private PropertyWatchChain watch;

        #endregion

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="PropertyWatchTrigger"/> class.
        /// </summary>
        /// <param name="watch">The watch.</param>
        public PropertyWatchTrigger(PropertyWatchChain watch)
        {
            if (watch == null)
                throw new ArgumentNullException("watch");
            this.watch = watch;
            watch.WatchedPropertyChanged += new EventHandler<EventArgs>(watch_WatchedPropertyChanged);
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="PropertyWatchTrigger"/> class.
        /// </summary>
        /// <param name="watch">The watch.</param>
        /// <param name="action">The action.</param>
        public PropertyWatchTrigger(PropertyWatchChain watch, Action action)
            : this(watch)
        {
            this.Action = action;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="PropertyWatchTrigger"/> class.
        /// </summary>
        /// <param name="watch">The watch.</param>
        /// <param name="action">The action.</param>
        /// <param name="source">The source.</param>
        public PropertyWatchTrigger(PropertyWatchChain watch, Action action, INotifyPropertyChanged source)
            : this(watch, action)
        {
            this.Source = source;
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets or sets the action.
        /// </summary>
        /// <value>
        /// The action.
        /// </value>
        public Action Action { get; set; }

        /// <summary>
        /// Gets or sets the source.
        /// </summary>
        /// <value>
        /// The source.
        /// </value>
        public INotifyPropertyChanged Source
        {
            get { return watch.Head.Source; }
            set { watch.Head.Source = value; }
        }

        #endregion

        #region Methods

        /// <summary>
        /// Handles the WatchedPropertyChanged event of the watch control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        void watch_WatchedPropertyChanged(object sender, EventArgs e)
        {
            if (this.Action != null)
                this.Action();
        }

        #endregion
    }
}
